﻿using Dapper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IRepository;
using ProTrack.IRepository.WareHouse;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProTrack.Repository.WareHouse
{
    public class QcReceiveRecordRepository: IQcReceiveRecordRepository
    {
        public QcReceiveRecordRepository(IBaseConnection baseConnection, IBaseRepository db)
        {

            Db = db;
            BaseConnection = baseConnection.GetConn();
        }

        public IBaseRepository Db { get; }
        public SqlConnection BaseConnection { get; }


        public async Task<bool> AddQcReceiveRecord(QcReceiveRecord model, List<QcReceiveRecordItemDto> list)
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {
                    // 主表 模型
                    var type = model.GetType();

                    var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
                    var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));
                    //剔除Id 
                    Field = Field.Substring(Field.IndexOf("Id,") + 3);
                    Values = Values.Substring(Values.IndexOf($"@Id,") + 4);

                    string Sql = $"Insert into {type.Name}({Field}) values ({Values});Select @@Identity;";

                    //插入主表，获取自增列Id
                    var QcReceiveRecordId = await BaseConnection.ExecuteScalarAsync(Sql, model, tran);
                    if (list.Count>0)
                    {
                        foreach (var item in list)
                        {
                            //为QcReceiveRecordId赋值
                            item.RecordId = Convert.ToInt64(QcReceiveRecordId);
                            QcReceiveRecordItem cc = new QcReceiveRecordItem()
                            {
                                Device= item.Device,
                                Classify= item.Classify,
                                Id= item.Id,
                                ProjectCode= item.ProjectCode,
                                ProjectName= item.ProjectName,
                                RecordId= item.RecordId,
                                Remark= item.Remark,
                                StandUnit= item.StandUnit,
                                StandValue= item.StandValue,
                                Status= item.Status,
                            };
                            // 主表 模型

                            var type2 = cc.GetType();

                            var Field2 = string.Join(',', type2.GetProperties().Select(p => p.Name));
                            var Values2 = string.Join(',', type2.GetProperties().Select(p => "@" + p.Name));
                            //剔除Id 
                            Field2 = Field2.Substring(Field2.IndexOf("Id,") + 3);
                            Values2 = Values2.Substring(Values2.IndexOf($"@Id,") + 4);

                            string Sql2 = $"Insert into {type2.Name}({Field2}) values ({Values2});Select @@Identity;";

                            //插入主表，获取自增列Id
                            var QcReceiveRecordItemId = await BaseConnection.ExecuteScalarAsync(Sql2, item, tran);

                            if (item.Children.Count>0)
                            {
                                foreach (var item2 in item.Children)
                                {
                                    //为QcReceiveRecordId赋值
                                    item2.QcReceiveRecordItemId = Convert.ToInt64(QcReceiveRecordItemId);
                                    QcReceiveRecordItemDetails dd = new QcReceiveRecordItemDetails()
                                    {
                                        Count= item2.Count,
                                        Id= item2.Id,
                                        LevelName= item2.LevelName,
                                        QcProjectLevel= item2.QcProjectLevel,
                                        QcReceiveRecordItemId= item2.QcReceiveRecordItemId,
                                        Remark= item2.Remark,
                                    };
                                    

                                    // 主表 模型
                                    var type3 = dd.GetType();

                                    var Field3 = string.Join(',', type3.GetProperties().Select(p => p.Name));
                                    var Values3 = string.Join(',', type3.GetProperties().Select(p => "@" + p.Name));
                                    //剔除Id 
                                    Field3 = Field3.Substring(Field3.IndexOf("Id,") + 3);
                                    Values3 = Values3.Substring(Values3.IndexOf($"@Id,") + 4);
                                    string Sql3 = $"Insert into {type3.Name}({Field3}) values ({Values3})";

                                    await BaseConnection.ExecuteAsync(Sql3, item2, tran);
                                }
                            }
                        }

                    }



                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        public async Task<bool> UpdateQcReceiveRecord(QcReceiveRecord model, List<QcReceiveRecordItemDto> list)
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {


                    //删除当前来料检验单子项
                    await BaseConnection.ExecuteAsync("delete QcReceiveRecordItemDetails where QcReceiveRecordItemId in (select Id from QcReceiveRecordItem where RecordId=@Id);delete QcReceiveRecordItem where RecordId=@Id", new { model.Id }, tran);

                    var type = model.GetType();
                    var modelName = type.Name;

                    var Field = string.Join(',', type.GetProperties().Select(p => $"{p.Name}=@{p.Name}"));
                    //剔除Id
                    Field = Field.Replace("Id=@Id,", "");
                    string Sql = $"update {type.Name} set {Field}  where Id=@Id";
                    await BaseConnection.ExecuteAsync(Sql, model, tran);

                    if (list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            //为QcReceiveRecordId赋值
                            item.RecordId = model.Id;
                            QcReceiveRecordItem cc = new QcReceiveRecordItem()
                            {
                                Device = item.Device,
                                Classify = item.Classify,
                                Id = item.Id,
                                ProjectCode = item.ProjectCode,
                                ProjectName = item.ProjectName,
                                RecordId = item.RecordId,
                                Remark = item.Remark,
                                StandUnit = item.StandUnit,
                                StandValue = item.StandValue,
                                Status = item.Status,
                            };
                            // 主表 模型

                            var type2 = cc.GetType();

                            var Field2 = string.Join(',', type2.GetProperties().Select(p => p.Name));
                            var Values2 = string.Join(',', type2.GetProperties().Select(p => "@" + p.Name));
                            //剔除Id 
                            Field2 = Field2.Substring(Field2.IndexOf("Id,") + 3);
                            Values2 = Values2.Substring(Values2.IndexOf($"@Id,") + 4);

                            string Sql2 = $"Insert into {type2.Name}({Field2}) values ({Values2});Select @@Identity;";

                            //插入主表，获取自增列Id
                            var QcReceiveRecordItemId = await BaseConnection.ExecuteScalarAsync(Sql2, item, tran);

                            if (item.Children.Count > 0)
                            {
                                foreach (var item2 in item.Children)
                                {
                                    //为QcReceiveRecordId赋值
                                    item2.QcReceiveRecordItemId = Convert.ToInt64(QcReceiveRecordItemId);
                                    QcReceiveRecordItemDetails dd = new QcReceiveRecordItemDetails()
                                    {
                                        Count = item2.Count,
                                        Id = item2.Id,
                                        LevelName = item2.LevelName,
                                        QcProjectLevel = item2.QcProjectLevel,
                                        QcReceiveRecordItemId = item2.QcReceiveRecordItemId,
                                        Remark = item2.Remark,
                                    };


                                    // 主表 模型
                                    var type3 = dd.GetType();

                                    var Field3 = string.Join(',', type3.GetProperties().Select(p => p.Name));
                                    var Values3 = string.Join(',', type3.GetProperties().Select(p => "@" + p.Name));
                                    //剔除Id 
                                    Field3 = Field3.Substring(Field3.IndexOf("Id,") + 3);
                                    Values3 = Values3.Substring(Values3.IndexOf($"@Id,") + 4);
                                    string Sql3 = $"Insert into {type3.Name}({Field3}) values ({Values3})";

                                    await BaseConnection.ExecuteAsync(Sql3, item2, tran);
                                }
                            }
                        }

                    }



                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    throw ex;
                }
            }
        }
    }
}
